package edu.ycu.aladdin.common.dao.impl;

import com.mongodb.client.result.UpdateResult;
import edu.ycu.aladdin.common.constant.MongoConstant;
import edu.ycu.aladdin.common.dao.NewsDataDao;
import edu.ycu.aladdin.common.entity.Label;
import edu.ycu.aladdin.common.entity.News;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
@Slf4j
public class NewsDataDaoImpl implements NewsDataDao, MongoConstant {

    private final MongoTemplate mongoTemplate;

    public NewsDataDaoImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void save(News news) {
        mongoTemplate.insert(news, NEWS_COLLECTION);
    }

    @Override
    public void addLabel(String id, Label label) {

        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.addToSet("labels",label);
        UpdateResult result = mongoTemplate.upsert(query, update, NEWS_COLLECTION);
        log.info("添加标签匹配数据id:{},查询数据{}条,修改数据{}条"
                ,id,result.getMatchedCount(),result.getModifiedCount());
    }

    // TODO
    @Override
    public void update(News news) {

    }

    @Override
    public List<News> findDataWithSmallLabel(int limit,String uid) {

        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("labels").elemMatch(Criteria.where("labeler").ne(uid))),
                Aggregation.project("content").and("labels").size().as("labelSize"),
                Aggregation.sort(Sort.Direction.ASC,"labelSize"),
                Aggregation.limit(limit)
        );
        log.debug("用户标注数量较小的数据查询条件:{}",aggregation.toString());
        return mongoTemplate.aggregate(aggregation, NEWS_COLLECTION, News.class).getMappedResults();
    }
}
